package com.Rpc远程调用简单版.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.lang.reflect.Method;

import java.net.Socket;


public class RpcInvocationServerHandler implements  Runnable {



    private    Socket socket ;

    public RpcInvocationServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {


        System.out.println("有链接进入"+socket.getInetAddress().getHostName());

        ObjectInputStream objectInputStream =null ;


        ObjectOutputStream objectOutputStream = null;


        try{

            objectInputStream  = new ObjectInputStream( socket.getInputStream());

            String className =objectInputStream.readUTF();

            String methodName =objectInputStream.readUTF();


           Class<?> [] parameterTypes  = (Class<?>[]) objectInputStream.readObject();


           Object[] arguments = (Object[]) objectInputStream.readObject();



           Class service = ServiceRegister.lookFor(className);

           Method method = service.getMethod(methodName,parameterTypes);


           Object obj = method.invoke(service.newInstance(),arguments);



           objectOutputStream = new ObjectOutputStream(socket.getOutputStream());

           objectOutputStream.writeObject(obj);

           objectOutputStream.flush();


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            if(objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
